package controller

import (
	"context"
	"errors"
	"strings"

	"v8s-ssp-proxy/internal/types"
)

func (c *controller) handleFunctionMessage(ctx context.Context, msg types.SSPPartnerMessage) {
	steps := make(chan types.Step, c.properties.Concurrency)
	errs := make(chan error)
	projectCode := namespacePrefix + strings.ToLower(strings.ReplaceAll(strings.ReplaceAll(msg.ProjectCode, "_", "-"), " ", "-"))

	go func() {
		// range until stepChan is closed
		for step := range steps {
			c.writeStep(step, msg, projectCode)
			continue
		}

		// when stepChan is closed we got through cycle and check if err is occurred
		err := <-errs
		if err != nil {
			c.log.With("rqUUID", msg.RqUUID).Errorf("handle message error: %s", err)
			return
		} else {
			c.log.With("rqUUID", msg.RqUUID).Info("instance successfully handled")
			return
		}
	}()

	var err error

	resourceCode, err := resourceCode(msg.ResourceId)
	if err != nil {
		// stepChan <- types.Step{Name: stepINIT, Error: true, Content: map[string]string{"error": err.Error()}}
		close(steps)
		errs <- err
		return
	}

	switch msg.FunctionCode {
	case functionCodeConnect:
		var composeJSON, taskName string
		composeJSON, taskName, err = getConnectContent(msg.Content)
		if err != nil {
			steps <- types.Step{Name: stepINIT, Error: true, Content: map[string]string{"error": err.Error()}}
			close(steps)
			errs <- err
			return
		}
		err = c.handlers.CreateTask(ctx, steps, msg.ResourceId, resourceCode, composeJSON, projectCode, msg.ResourceId, taskName)
	case functionCodeDelete:
		err = c.handlers.DeleteTask(ctx, steps, projectCode, msg.ResourceId)
	case functionCodePause:
		err = c.handlers.StopTask(ctx, steps, projectCode, msg.ResourceId)
	case functionCodeResume:
		err = c.handlers.ResumeTask(ctx, steps, projectCode, msg.ResourceId)
	default:
		errs <- errors.New("unknown function code specified in msg")
		return
	}

	if err != nil {
		close(steps)
		errs <- err
		return
	}

	// closing stepChan here, cause we already sent everything we need after exiting Order method
	close(steps)
}
